package com.system.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by 54110 on 2020/8/19.
 */
@RestController
public class AlipayController {

    @RequestMapping("/pay")
    @ResponseBody
    public String pay(HttpServletRequest httpRequest,
                      HttpServletResponse httpResponse) throws ServletException, IOException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do", "2016101800712391", "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCmWP7jO+ygVgmPZak6MmmiuH1/nhwfCbTsB4huKpwa0t9YG1rfRGiOsOe2THs1GPYvAZXxEHzmAHE+Qfkk7UxhfXqst8zivQ0F1ky3FWzKUkVYT5Ebp2nYFGUkGUcNugQUiLHhHOiHVtSnc6IR8AJpJ7PRXVph7KvEst8FUipIVolklo15O7q8pimooqWMURFg/4EmsT5ErQ7ZA7gEbhNpeSzHNc7PR0HT39pgK2bgwL4y6OfRrNLcZsyFM4RcZsLqgcTuNYb/GwtOyHdNtF91g8CT4hz7S4K0PdRfjy4YNar7EUr2W881HQVDdWG+8X/pxnoOHbvWwoZ9vuG7egBZAgMBAAECggEASXQk4RxV6Zr0T8C5UDxwjuzeZdrgWghEPrE42kSwd9vDybkSkGI5tUCCoOn2wcSK+Mi/eBoqvLlXSAGDzX2Ha8knwVrL+xc1x+0QJQwt5M0dV9iSn952C3c+DgmnaXVJVfPicB/+wbxi3Kpf14He3qYsbffF8FW8p3fAqS3WA+iTvk7329lIcnO9dZED3Z0p69WUuI409QFbHpFryBFg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SYQKWGiGopysy9KoHluqrsasGqDZWBm8Q4WlDYXpRpV7C53fqbChz/p/VwdGpb+bDSZU9pLEaSCzZTX6JqEeFo2fQav4mRVIY1FPgqOJ5Mn4AN/dB7j45Qy9wrIKh6+nP3dvDiN4wrHiobj4cl8Xb4vxbI3bvbj2SFYeL6u8iO49Hi4oXHvNaNzoKw8tl2hkI8N5sWU4LZAdT8odCSdpWwoMRvAapN+Doa4ceRgBmSc9D6l2qfz8Y0DIjd9wrs2fAc0XUUxb+JG1p5wGnzDagaNxFO8YkfeKlnaLtQ2ELQ2cy25db6sdNihIvXs6J3RzaU9kB4lHZwIDAQAB", "RSA2");  //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); //创建API对应的request

        //alipayRequest.setReturnUrl( "http://331t2j2729.zicp.vip/returlCallBack" );
        //支付宝的回调地址,支付结果异步通知
        alipayRequest.setNotifyUrl("http://331t2j2729.zicp.vip/returlCallBack"); //在公共参数中设置回跳和通知地址
        //alipayRequest.putOtherTextParam("app_auth_token", "201611BB8xxxxxxxxxxxxxxxxxxxedcecde6");//如果 ISV 代商家接入电脑网站支付能力，则需要传入 app_auth_token，使用第三方应用授权；自研开发模式请忽略
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\"123456789009876542222222222\"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":88.88," +
                "    \"subject\":\"玛莎拉蒂\"," +
                "    \"body\":\"随便来\"," +
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                "    \"extend_params\":{" +
                "    \"sys_service_provider_id\":\"2088511833207846\"" +
                "    }" +
                "  }"); //填充业务参数
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return form;
    /*    httpResponse.setContentType( "text/html;charset="  + "utf-8");
        httpResponse.getWriter().write(form); //直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();*/
    }


    @RequestMapping("/returlCallBack")
    public String returlCallBack(HttpServletRequest request) throws AlipayApiException {
        Map<String, String> paramsMap = convertRequestParamsToMap(request);
        boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAol4SrTwjB6RqSYQKWGiGopysy9KoHluqrsasGqDZWBm8Q4WlDYXpRpV7C53fqbChz/p/VwdGpb+bDSZU9pLEaSCzZTX6JqEeFo2fQav4mRVIY1FPgqOJ5Mn4AN/dB7j45Qy9wrIKh6+nP3dvDiN4wrHiobj4cl8Xb4vxbI3bvbj2SFYeL6u8iO49Hi4oXHvNaNzoKw8tl2hkI8N5sWU4LZAdT8odCSdpWwoMRvAapN+Doa4ceRgBmSc9D6l2qfz8Y0DIjd9wrs2fAc0XUUxb+JG1p5wGnzDagaNxFO8YkfeKlnaLtQ2ELQ2cy25db6sdNihIvXs6J3RzaU9kB4lHZwIDAQAB", "utf-8", "RSA2"); //调用SDK验证签名
        if (signVerified) {
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            System.out.println(paramsMap);
            return "success";
        } else {
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            return "fail";
        }
    }

    // 将request中的参数转换成Map
    private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }
}
